package smetana;

import com.google.inject.Inject;

import org.apache.pivot.collections.Map;
import org.apache.pivot.wtk.Application;
import org.apache.pivot.wtk.Application.AboutHandler;
import org.apache.pivot.wtk.Display;
import org.apache.pivot.wtk.TablePane;
import org.apache.pivot.wtk.Window;
import org.apache.pivot.wtkx.WTKXSerializer;
import smetana.modules.App;
import smetana.modules.ui.actions.AboutAction;
import smetana.modules.ui.form.search.ShowExceptionDialog;
import smetana.modules.ui.form.window.MainMenuPanel;
import smetana.modules.ui.form.window.ToolbarPanel;
import smetana.modules.ui.form.window.WorkPanel;
import smetana.modules.ui.model.UIModel;

/**
 *
 * @author dmitry.mamonov
 */
public class Smetana implements Application, AboutHandler, Application.UncaughtExceptionHandler {

    @Inject
    private MainMenuPanel mainMenuPanel;
    @Inject
    private ToolbarPanel toolbarPanel;
    @Inject
    private WorkPanel workPanel;
    private Window window = null;

    @Inject
    AboutAction actionAbout;

    @Inject
    UIModel uiModel;

    //TODO what about before startup method which will be called before display is displayed.    
    @Override
    public void startup(Display display, Map<String, String> properties)
            throws Exception {
        App.injector().injectMembers(this);
        WTKXSerializer wtkx = new WTKXSerializer();
        window = (Window) wtkx.readObject(this, "/smetana/modules/ui/form/window/WindowMain.wtkx");
        {
            window.setIcon(getClass().getResource("/smetana/modules/ui/form/res/bookcase.png"));
        }
        { //configure UI model.
            uiModel.setWindow(window);
        }
        {
            TablePane.Row row = wtkx.getValue("menuRow");
            row.add(mainMenuPanel.getComponent());
        }
        {
            TablePane.Row row = wtkx.getValue("toolbarRow");
            row.add(toolbarPanel.getComponent());
        }
        {
            TablePane.Row row = wtkx.getValue("workRow");
            row.add(workPanel.getComponent());
        }
        window.open(display);
    }

    @Override
    public boolean shutdown(boolean optional) {
        if (window != null) {
            window.close();
        }

        return false;
    }

    @Override
    public void suspend() {
    }

    @Override
    public void resume() {
    }

    @Override
    public void aboutRequested() {
        actionAbout.perform();
    }

    @Override
    public void uncaughtExceptionThrown(Exception exception) {
        exception.printStackTrace();
        ShowExceptionDialog dialogShowException = new ShowExceptionDialog();
        dialogShowException.setThrowable(exception);
        dialogShowException.getDialog().open(window);
    }
}
